package prjCode;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class OrderResults {


	public static class MapClass extends Mapper<LongWritable, Text, FloatWritable, Text> {

		Text val = new Text();
		FloatWritable k = new FloatWritable();
		
		@Override
		public void map(LongWritable key, Text value, Context context) throws IOException,  InterruptedException {
			
			String line = value.toString();
			val.set(line.substring(line.indexOf("\t") + 1));
			k.set(Float.valueOf(line.substring(0, line.indexOf("\t"))));
			context.write(k, val);		
		}

	}

	public static class ReduceClass extends Reducer<FloatWritable ,Text,FloatWritable ,Text> {

		
		@Override
		public void reduce(FloatWritable key, Iterable<Text> values, Context context) throws IOException,  InterruptedException {

			

			for (Text value : values) {
				context.write(key ,value);
			}
			

		}
	}

	

	public static class PartitionerClass extends Partitioner<FloatWritable, Text> {
		// ensure that keys with same key are directed to the same reducer
		@Override
		public int getPartition(FloatWritable key,Text value, int numPartitions) {
			return  Math.abs(key.hashCode()) % numPartitions;
		}
	}

	public static void main(String[] args) throws Exception {



		Configuration conf = new Configuration();
		Job job = new Job(conf, "Order results");
		job.setJarByClass(OrderResults.class);
		job.setMapperClass(OrderResults.MapClass.class);
		job.setPartitionerClass(OrderResults.PartitionerClass.class);
		job.setReducerClass(OrderResults.ReduceClass.class);
		job.setOutputKeyClass(FloatWritable.class);
		job.setOutputValueClass(Text.class);
		job.setMapOutputKeyClass(FloatWritable.class);
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}


}
